<?php

namespace IMooc;

use App\Model\MUser;

/**
 * 工厂模式
 */
class Factory
{
    static mixed $proxy = null;

    static function createDatabase(): Database
    {
        $db = new Database;
        Register::set('db1', $db);
        return $db;
    }

    /**
     * 使用注册模式，共用一个ORM类对象，避免重复实例化
     * @param $id
     * @return MUser
     * @author lintong
     * @created 2023/9/12 18:39
     */
    static function getUser($id): MUser
    {
        $key = 'user_' . $id;
        $user = Register::get($key);
        if (!$user) {
            $user = new MUser($id);
            Register::set($key, $user);
        }
        return $user;
    }

    /**
     * @param $name
     * @return mixed|null
     */
    static function getModel($name): mixed
    {
        $key = 'app_model_' . $name;
        $model = Register::get($key);
        if (!$model) {
            $class = '\\App\\Model\\' . ucwords($name);
            $model = new $class;
            Register::set($key, $model);
        }
        return $model;
    }

    static function getDatabase($id = 'proxy')
    {
        if ($id == 'proxy') {
            if (!self::$proxy) {
                self::$proxy = new \IMooc\Database\Proxy;
            }
            return self::$proxy;
        }

        $key = 'database_' . $id;
        if ($id == 'slave') {
            $slaves = Application::getInstance()->config['database']['slave'];
            $db_conf = $slaves[array_rand($slaves)];    // 随机获取从数据库
        } else {
            $db_conf = Application::getInstance()->config['database'][$id];
        }
        $db = Register::get($key);
        if (!$db) {
            $db = new Database\MySQLi();
            $db->connect($db_conf['host'], $db_conf['user'], $db_conf['password'], $db_conf['dbname']);
            Register::set($key, $db);
        }
        return $db;
    }
}